#include <iostream>
#include <string>
#include <unistd.h>
#include <mysql/mysql.h>

using namespace std; // g++ -o mytest test.cc -L/lib64/mysql -lmysqlclient

const string host = "127.0.0.1";
const string user = "connector";
const string passwd = "123456";
const string db = "conn";
unsigned int port = 3306;

int main()
{
    // 尝试链接mysql client
    // 通过 mysql_get_client_info() 函数，来验证我们的引入是否成功
    // std::cout << "mysql client version: " << mysql_get_client_info() << std::endl;

    MYSQL* my = mysql_init(nullptr);
    if(my == nullptr)
    {
        cerr << "Init MySQL error" << endl;
        return 1;
    }
    if(mysql_real_connect(my,host.c_str(),user.c_str(),passwd.c_str(),db.c_str(),port,nullptr,0) == nullptr)
    {
        cerr << "connection MySQL error" << endl;
        return 2;
    }
    // cout << "MySQL connection success" << endl;
    // sleep(10);

    mysql_set_character_set(my,"utf8");
    // string sql = "insert into user(name,age,telphone) values('张三',18,'1243124832')";
    // string sql = "delete from user where id=1";
    // string sql = "update user set name='jam' where id=2";
    string sql = "select * from user";

    int n = mysql_query(my,sql.c_str());
    if(n == 0) cout << sql << "success:" << n << endl;
    else 
    {
        cout << sql << "fail:" << n << endl;
        return 3;
    }
    // 把MYSQL结构体中的获取到的数据，放到MYSQL_RES结构体
    MYSQL_RES* res = mysql_store_result(my);
    if(nullptr == res)
    {
        cout << "mysql_store_result error" << endl;
        return 4;
    }
    // 下面全部是和结果集有关的，MYSQL_RES
    int rows = mysql_num_rows(res);
    int fields = mysql_num_fields(res);
    cout << "行：" << rows << endl;
    cout << "列：" << fields << endl;

    // 属性
    MYSQL_FIELD* fields_arry = mysql_fetch_fields(res);
    for(int i = 0; i < fields; i++)
    {
        cout << fields_arry[i].name << "\t";
    }
    cout << endl;

    // 内容
    for(int i = 0; i < rows; ++i)
    {
        MYSQL_ROW row = mysql_fetch_row(res);
        for(int j = 0; j < fields; ++j)
        {
            cout << row[j] << "\t";
        }
        cout << endl;
    }

    // string sql = "";
    // while(true)
    // {
    //     cout << ">>";
    //     if(sql == "quit" || !getline(cin,sql))
    //     {
    //         cout << "Bey" << endl;
    //         break;
    //     }
    //     int n = mysql_query(my,sql.c_str());
    //     if(n == 0) cout << sql << "success:" << n << endl;
    //     else cout << sql << "fail:" << n << endl;
    // }

    mysql_close(my);
    return 0;
}
